package edu.neu.cs6515.board.rules;

import edu.neu.cs6515.board.BoardCoord;
import edu.neu.cs6515.board.HexagonBoard;
import edu.neu.cs6515.xml.Placement;

/**
 * Validates a tile: both coordinates are within the board and they are
 * neighbors
 */
public final class LegalTileRule extends Rule {

    public static final String REASON = "ILLEGAL-TILE";

    /**
     * Init class with board obj
     * 
     * @param board
     *            the board to be used for validation
     */
    public LegalTileRule(final HexagonBoard board) {
        super(board);
    }

    /**
     * validate whether the placement satisfy the given rule
     * 
     * @param p
     *            placement to be validated
     * @return true if the Placement is valid
     */
    @Override
    public boolean validate(final Placement p) {
        if (isLegalHexagon(p.getD0(), p.getA0())
                && isLegalHexagon(p.getD1(), p.getA1())) {
            return board.isNeighbor(new BoardCoord(p.getD0(), p.getA0()),
                    new BoardCoord(p.getD1(), p.getA1()));
        }
        return false;
    }

    /**
     * determines if angle and distance indicates a legal hexagon on the board
     * 
     * @param distance
     *            to check
     * @param angle
     *            to check
     * 
     * @return true if dist and ang are within bounds
     */
    private boolean isLegalHexagon(final int distance, final int angle) {
        return (distance >= 0 && distance <= board.getMaxDistance())
                && (angle >= 0 && angle <= board.getHighestAngle(distance));
    }

    @Override
    public String getReason() {
        return REASON;
    }
}
